package cc.yugu.yhdw.common.web.controller;

import cc.yugu.yhdw.common.spring.DateEditor;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
/**
 * 公共的控制层类
 *
 * @Date:Created in 2018/7/5 11:59
 * @Author:
 * @Modified By: zxj 2018/7/5 11:59
 */
public class AbstractController {
    /**
     * 参数绑定格式化
     * @Param [binder]
     * @Return void
     * @Author zxj 2018/7/5
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor());
    }
    /**
     * 下载支持（浏览器兼容校验）
     * @Param [file, request, response, fileName]
     * @Return void
     * @Author zxj 2018/7/5
     */
    protected void downloadSupport(File file, HttpServletRequest request, HttpServletResponse response, String fileName) throws IOException {
        // 获取浏览器参数
        String agent = request.getHeader("User-Agent");
        if (agent != null) {
            // 字符串格式化小写
            agent = agent.toLowerCase();
            // msie为IE浏览器
            if (agent.indexOf("firefox") != -1) {
                fileName = new String(fileName.getBytes(),"ISO-8859-1");
            } else if (agent.indexOf("msie") != -1) {
                fileName = java.net.URLEncoder.encode(fileName,"UTF-8");
            } else {
                fileName = java.net.URLEncoder.encode(fileName,"UTF-8");
            }
        }
        // 响应的表头
        response.setHeader("Content-disposition", String.format("attachment;filename=%s", fileName));
        // .*（ 二进制流，不知道下载文件类型）
        response.setContentType("application/octet-stream");
        response.setBufferSize(1024 * 10);
        // 创建文件字节读取流
        FileInputStream inputStream = null;
        try {
            // 读取file
            inputStream = new FileInputStream(file);
            byte[] buf = new byte[1024 * 10];
            int count = -1;
            while( (count = inputStream.read(buf)) != -1) {
                response.getOutputStream().write(buf, 0, count);
            }
        } catch (Exception e) {
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
